package com.ln.lnzw.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.library.banner.BannerLayout;
import com.ln.lnzw.R;
import com.ln.lnzw.activity.ApprovalPublicityActivity;
import com.ln.lnzw.activity.ConsultationReplyActivity;
import com.ln.lnzw.activity.HandleaffairsServiceActivity;
import com.ln.lnzw.activity.HandleaffairsServiceFormsActivity;
import com.ln.lnzw.activity.HotlineActivity;
import com.ln.lnzw.activity.InquiriesActivity;
import com.ln.lnzw.activity.InteractionActivity;
import com.ln.lnzw.activity.UserAgreementActivity;
import com.ln.lnzw.adapter.HandleAffairsGridAdapter;
import com.ln.lnzw.adapter.HotItemsAdapter;
import com.ln.lnzw.adapter.WebBannerAdapter;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseFragment;
import com.ln.lnzw.bean.HotItemsBean;
import com.ln.lnzw.bean.ItemBean;
import com.ln.lnzw.bean.StatisticsBean;
import com.ln.lnzw.bean.WcmBean;
import com.ln.lnzw.net.HttpMethods;
import com.ln.lnzw.utils.StatusBarUtils;
import com.ln.lnzw.utils.ToastFactory;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wuwei on 2018/3/21.
 * 办事
 */

public class HandleAffairsFragment extends BaseFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    @BindView(R.id.fake_status_bar)
    ImageView fakeStatusBar;
    @BindView(R.id.tv_benyueshenqing)
    TextView tvBenyueshenqing;
    @BindView(R.id.tv_benyueshouli)
    TextView tvBenyueshouli;
    @BindView(R.id.tv_benyuejieban)
    TextView tvBenyuejieban;
    @BindView(R.id.tv_leijishenqing)
    TextView tvLeijishenqing;
    @BindView(R.id.tv_leijishouli)
    TextView tvLeijishouli;
    @BindView(R.id.tv_leijibanjie)
    TextView tvLeijibanjie;
    @BindView(R.id.tv_yidishenbaobili)
    TextView tvYidishenbaobili;
    @BindView(R.id.tv_gongzuoshijianwaishenbaobili)
    TextView tvGongzuoshijianwaishenbaobili;
    private HandleAffairsGridAdapter haAdapter;
    private List<ItemBean> listData = new ArrayList<>();//首页gridview数据集合
    private List<WcmBean.ListDatasBean> mlist = new ArrayList<>();//首页轮播数据集合
    private List<String> list = new ArrayList<>();//首页轮播数据集合
    private List<HotItemsBean.ResultBean> list1 = new ArrayList<>();//热门事项数据集合
    private HotItemsAdapter hiAdapter;
    private WebBannerAdapter webBannerAdapter;
    private BannerLayout recyclerBanner;

    public static HandleAffairsFragment newInstance() {
        Bundle args = new Bundle();
        HandleAffairsFragment fragment = new HandleAffairsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.handleaffairsfragment_activity, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        StatusBarUtils.statusBar(fakeStatusBar);

        initData();//轮播图
        initHotItems();//热门事项
        initOffice();//办件统计
        recyclerBanner = activity.findViewById(R.id.recycler);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) recyclerBanner.getLayoutParams();
        layoutParams.height = ScreenUtils.getScreenHeight() / 4;
        layoutParams.width = ScreenUtils.getScreenWidth();
        recyclerBanner.setLayoutParams(layoutParams);

        RecyclerView recyclerView = activity.findViewById(R.id.rv_recyclerview);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new GridLayoutManager(activity, 4));
        haAdapter = new HandleAffairsGridAdapter(R.layout.item_handleaffairs, listData);
        recyclerView.setAdapter(haAdapter);
        recyclerView.addOnItemTouchListener(new OnItemClickListener() {

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == 0) {
                    ActivityUtils.startActivity(activity, HandleaffairsServiceActivity.class);
                }
                if (position == 2) {
                    ActivityUtils.startActivity(activity, ApprovalPublicityActivity.class);
                }
                if (position == 3) {
                    ActivityUtils.startActivity(activity, InteractionActivity.class);
                }
                if (position == 4) {
                    ActivityUtils.startActivity(activity, InquiriesActivity.class);
                }
                if (position == 6) {
                    ActivityUtils.startActivity(activity, ConsultationReplyActivity.class);
                }
                if (position == 7) {
                    ActivityUtils.startActivity(activity, HotlineActivity.class);
                }

            }
        });

        RecyclerView rvViewHotItems = activity.findViewById(R.id.rv_hotitems);
        rvViewHotItems.setNestedScrollingEnabled(false);
        rvViewHotItems.setLayoutManager(new LinearLayoutManager(activity));
        hiAdapter = new HotItemsAdapter(R.layout.item_hotitems, list1);
        rvViewHotItems.setAdapter(hiAdapter);
        rvViewHotItems.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle b  = new Bundle();
                b.putString("itemId",list1.get(position).getItemCode());
                Log.i("000", "onSimpleItemClick: "+list1.get(position).getItemCode());
                b.putString("itemCode",list1.get(position).getItemCode());
                b.putString("itemTitle",list1.get(position).getProcessName());
                ActivityUtils.startActivity(b,HandleaffairsServiceFormsActivity.class);
            }
        });
        //屏蔽上拉加载
        refreshLayout.setEnableLoadMore(false);
        //设置下拉刷新监听事件
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        //结束加载
                        refreshLayout.finishRefresh();
//                        //加载失败的话3秒后结束加载
//                        refreshLayout.finishRefresh(3000);
                    }
                }, 3000);
            }
        });
    }

    private void initHotItems() {
        HttpMethods.getInstance().info.getHotItems(AppConstant.BASE_URL+"app/public/popularApproval")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HotItemsBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HotItemsBean hotItemsBean) {
                        if (list1 != null || !list1.isEmpty()) {
                            list1.clear();
                        }
                        if ("200".equals(hotItemsBean.getCode())){
                            list1.addAll(hotItemsBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        hiAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void initOffice() {
        HttpMethods.getInstance().info.getStatistics(AppConstant.BASE_URL+"app/public/officeStatistics")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StatisticsBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(StatisticsBean statisticsBean) {
                        Log.i("555", "onNext: "+statisticsBean.toString());
                          if ("200".equals(statisticsBean.getCode())){
                              setValue(statisticsBean);
                          }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
    //设置办件统计的值
    private void setValue(StatisticsBean statisticsBean) {
        tvBenyueshenqing.setText("本月申请："+statisticsBean.getResult().getMonthAppli()+" 件");
        tvBenyueshouli.setText("本月受理："+statisticsBean.getResult().getMonthAccept()+" 件");
        tvBenyuejieban.setText("本月办结："+statisticsBean.getResult().getMonthFinish()+" 件");
        tvLeijishenqing.setText("累计申请："+statisticsBean.getResult().getTotalAppli()+" 件");
        tvLeijishouli.setText("累计受理："+statisticsBean.getResult().getTotalAccept()+" 件");
        tvLeijibanjie.setText("累计办结："+statisticsBean.getResult().getTotalFinish()+" 件");
        tvYidishenbaobili.setText("异地申报比例："+statisticsBean.getResult().getDeclarationRatio());
        tvGongzuoshijianwaishenbaobili.setText("工作时间外申报比例："+statisticsBean.getResult().getOutsideworkRatio());
    }


    private void initData() {
//        首页轮播数据
//        list.add("http://a3.topitme.com/1/21/79/1128833621e7779211o.jpg");
//        list.add("http://f9.topitme.com/9/37/30/11224703137bb30379o.jpg");
//        list.add("http://pic.58pic.com/58pic/15/24/50/43Q58PICkj4_1024.jpg");
//        list.add("http://pic10.nipic.com/20101001/2531170_011837344719_2.jpg");
//        list.add("http://pic17.nipic.com/20111021/8289149_105725398120_2.jpg");
//        list.add("http://pic21.nipic.com/20120528/7487615_092947555158_2.jpg");

        HttpMethods.getInstance().info.getWcmData(AppConstant.LUNBOPIC_URL)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WcmBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(WcmBean wcmBean) {
                        if (mlist != null || !mlist.isEmpty()) {
                            mlist.clear();
                        }
                        mlist.addAll(wcmBean.getList_datas());
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (list != null || !list.isEmpty()) {
                            list.clear();
                        }
                        list.add("");
                        list.add("");
                        list.add("");
                        webBannerAdapter = new WebBannerAdapter(activity, list);
                        recyclerBanner.setAdapter(webBannerAdapter);
                    }

                    @Override
                    public void onComplete() {
                        if (list != null || !list.isEmpty()) {
                            list.clear();
                        }
                        for (int i = 0; i < mlist.size(); i++) {
                            list.add(mlist.get(i).getCimgs().get(0));
                        }

                        webBannerAdapter = new WebBannerAdapter(activity, list);

                        webBannerAdapter.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                Bundle b = new Bundle();
                                b.putString("webUrl", mlist.get(position).getUrl());
                                ActivityUtils.startActivity(b, UserAgreementActivity.class);
                            }
                        });
//                        if (list.size()==0){
//                            list.add("");
//                            list.add("");
//                            list.add("");
//                        }
                        recyclerBanner.setAdapter(webBannerAdapter);
                    }
                });
        //首页gridview数据
        listData.add(new ItemBean("办事服务"));
        listData.add(new ItemBean("投资项目"));
        listData.add(new ItemBean("审批公示"));
        listData.add(new ItemBean("互动交流"));
        listData.add(new ItemBean("办件查询"));
        listData.add(new ItemBean("帮助手册"));
        listData.add(new ItemBean("资讯回复"));
        listData.add(new ItemBean("热线电话"));

//        list1.add("权限内肥料登记");
//        list1.add("对在药品生产企业所在地和进口药品代理机构所在地以外的省、自治区、直辖市发布药品广告的备案");
//        list1.add("建筑施工企业安全生产许可证核发");
//        list1.add("省级范围内危险化学品生产企业安全许可证核发（非中央企业及其直接控股涉及危险化学品生产企业（总部））");
//        list1.add("饲料添加剂、饲料添加剂预混合饲料产品批准文号核发");

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
